const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
const Order = require('../models/Order');
const Review = require('../models/Review');
const crypto = require('crypto');

// Webhook验证中间件
const verifyWebhook = (req, res, next) => {
    const signature = req.headers['x-wc-webhook-signature'];
    const payload = JSON.stringify(req.body);
    
    const expectedSignature = crypto
        .createHmac('sha256', process.env.WEBHOOK_SECRET || 'default-secret')
        .update(payload)
        .digest('base64');

    if (signature !== expectedSignature) {
        return res.status(401).json({ error: '无效的webhook签名' });
    }
    
    next();
};

// 处理产品更新webhook
router.post('/product', verifyWebhook, async (req, res) => {
    try {
        const productData = req.body;
        
        const [product, created] = await Product.upsert({
            woo_id: productData.id,
            name: productData.name,
            description: productData.description,
            price: parseFloat(productData.price),
            stock_quantity: productData.stock_quantity || 0,
            sku: productData.sku,
            category: productData.categories?.[0]?.name || '',
            tags: productData.tags?.map(tag => tag.name).join(', ') || '',
            images: JSON.stringify(productData.images?.map(img => img.src) || []),
            last_sync: new Date()
        }, {
            conflictFields: ['woo_id']
        });

        console.log(`产品 ${product.name} ${created ? '创建' : '更新'}成功`);
        res.json({ message: '产品同步成功', productId: product.id });
    } catch (error) {
        console.error('产品同步失败:', error);
        res.status(500).json({ error: error.message });
    }
});

// 处理订单创建webhook
router.post('/order', verifyWebhook, async (req, res) => {
    try {
        const orderData = req.body;
        
        const order = await Order.create({
            woo_id: orderData.id,
            customer_email: orderData.billing?.email || '',
            total_amount: parseFloat(orderData.total),
            status: orderData.status,
            order_date: orderData.date_created,
            items: JSON.stringify(orderData.line_items?.map(item => ({
                product_id: item.product_id,
                quantity: item.quantity,
                price: parseFloat(item.price)
            })) || []),
            shipping_address: JSON.stringify(orderData.shipping || {}),
            billing_address: JSON.stringify(orderData.billing || {})
        });

        console.log(`订单 ${order.woo_id} 创建成功`);
        
        // 检查库存预警
        for (const item of orderData.line_items || []) {
            const product = await Product.findOne({ where: { woo_id: item.product_id } });
            if (product && product.stock_quantity <= 10) {
                console.log(`库存预警: ${product.name} 库存为 ${product.stock_quantity}`);
                // 这里可以发送邮件通知
            }
        }

        res.json({ message: '订单同步成功', orderId: order.id });
    } catch (error) {
        console.error('订单同步失败:', error);
        res.status(500).json({ error: error.message });
    }
});

// 处理评论创建webhook
router.post('/review', verifyWebhook, async (req, res) => {
    try {
        const reviewData = req.body;
        
        const review = await Review.create({
            woo_id: reviewData.id,
            product_id: reviewData.product_id,
            customer_name: reviewData.reviewer,
            rating: reviewData.rating,
            comment: reviewData.review,
            review_date: reviewData.date_created
        });

        console.log(`评论 ${review.woo_id} 创建成功`);
        
        // 触发情感分析
        const { analyzeReview } = require('../services/aiService');
        await analyzeReview(review.id);

        res.json({ message: '评论同步成功', reviewId: review.id });
    } catch (error) {
        console.error('评论同步失败:', error);
        res.status(500).json({ error: error.message });
    }
});

// 健康检查端点
router.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

module.exports = router;
